package com.wondersgroup.core.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wondersgroup.core.mapper.InfoTraceDailyVisitMapper;
import com.wondersgroup.core.model.InfoTraceDailyVisit;
import com.wondersgroup.core.util.TimeOrDateUtils;

@Service
public class CountService {
	@Autowired
	private InfoTraceDailyVisitMapper itdMapper;

	
	/*
	 * 生成用户查询次数统计(用于定时任务)
	 */
	@Transactional(readOnly = false)
	public void calculateDailyVisit() {
		// 获取最后统计的时间（年月日）
		Date latestDate = itdMapper.getLatestDate();
		if (latestDate == null) {
			latestDate = new Date();
		}
		Date startDate = null;
		// 如果统计开始时间在今天，清除掉今天开始到现在的数据，重新计算
		if (latestDate.equals(TimeOrDateUtils.getDayBegin(new Date()))) {
			// 清空今天的统计数据
			InfoTraceDailyVisit dv = new InfoTraceDailyVisit();
			dv.setRequestDate(latestDate);
			itdMapper.delete(dv);
			startDate = latestDate;
		} else {//
			startDate = TimeOrDateUtils.getDateByOffsetDays(latestDate, 1);
		}
		// 统计新数据
		List<Map> countMap = itdMapper.getCountOfTraceHistoryOrderByCreateDate(startDate);
		// 保存统计数据
		for (Map map : countMap) {
			Object count = map.get("count");
			Object date = map.get("date");
			Object productType = map.get("productType");
			InfoTraceDailyVisit dv = new InfoTraceDailyVisit();
			dv.setCreateDate(new Date());
			dv.setLastModifiedDate(new Date());
			if (productType != null) {
				dv.setProductType(Integer.valueOf(String.valueOf(productType)));
			}
			if (count != null) {
				dv.setRequestCount(Integer.valueOf(String.valueOf(count)));
			}
			if (date != null) {
				dv.setRequestDate(TimeOrDateUtils.parseDate(String.valueOf(date)));
			}
			itdMapper.insert(dv);
		}
	}
	
	/**
	 * 获取食品十大类查询统计,默认计算30天以内
	 * @return 
	 */
	public List<Map<String, String>> getStatsOfQueryByProductType(int withinDays) {
		if(withinDays<1) {
			withinDays = 30;
		}
		List<Map<String, String>> statsOfQueryByProductType = itdMapper.getStatsOfQueryByProductType(withinDays);
		
		return statsOfQueryByProductType;
	}
	
	/**
	 * 获取食品十大类查询统计，之前两个月到今天
	 * @return 
	 */
	public List<Map<String, String>> getStatsOfQueryByDay() {
		List<Map<String, String>> result = itdMapper.getStatsOfQueryByDay();
		return result;
	}
	
}
